/*****************************************************************************
* Keppe Messenger (KMP) Keppe Project-Team User Messaging System
* Copyright (C) 2013-2014 Keppe Project-Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/

#include <QDir>
#include <QMap>
#include <QRgb>
#include <QMenu>
#include <QFile>
#include <QSize>
#include <QDebug>
#include <QSound>
#include <QTimer>
#include <QImage>
#include <KGuiFw>
#include <QBitmap>
#include <QPixmap>
#include <QPainter>
#include <QProcess>
#include <QSysInfo>
#include <QDateTime>
#include <QSettings>
#include <QHostInfo>
#include <KMsgFw111Q>
#include <QTcpSocket>
#include <QTranslator>
#include <QMessageBox>
#include <QCloseEvent>
#include <QInputDialog>
#include <QStyleFactory>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QSystemTrayIcon>
#include <QDesktopServices>
#include <QCryptographicHash>
#include <QSortFilterProxyModel>
#include "frmChat.h"
#include "frmLogin.h"
#include "frmConfig.h"
#include "frmProfile.h"
#include "frmAboutKMPQ.h"
#include "frmAboutKeppe.h"
#include "frmProfileInfo.h"
#include "frmChangePassword.h"
#include "frmContactRequests.h"
#include "NotificationWidget.h"
#include "ui_frmLogin.h"

#ifdef UPDATE_MANAGER
QAction *menu_CheckUpdate;
QAction *menu_HUSeperator;
#endif
QMenu *cStateMenu;
QMenu *menu_Messenger;
QMenu *menu_Onlinestatus;
QAction *menu_Online;
QAction *menu_Away;
QAction *menu_Busy;
QAction *menu_Notjust;
QAction *menu_Showoffline;
QAction *menu_M1Seperator;
QAction *menu_M2Seperator;
QAction *menu_Logout;
QAction *menu_AddContact;
QAction *menu_ChangePassword;
QAction *menu_EditProfile;
QAction *menu_ServerGroupChat;
QAction *menu_Close;
QMenu *menu_Tools;
QMenu *menu_Languages;
QAction *menu_A1Seperator;
QAction *menu_Config;
QMenu *menu_Help;
QAction *menu_AboutKeppe;
QAction *menu_AboutKMP;

frmLogin::frmLogin(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::frmLogin)
{
    ui->setupUi(this);
    this->setWindowTitle(ProductName);
    this->setWindowIcon(QIcon(ProductIcon));
    ui->labKMImage->setPixmap(QPixmap(ProductImg));
    defaultAvatar = QImage(":/gui/0-default.png");
    int stateID = 0;
    while(stateID != 8)
    {
        stateID++;
        stateLinkImage[stateID] = QImage(getIconPathForOnlineState(stateID));
    }
#ifndef MACX
    ui->menuBar->setHidden(true);
#endif
    ui->cmdStop->setVisible(false);
    ui->labDesignedLoginDes->setVisible(false);
    ui->labContactsSearchReset->setVisible(false);
    hostName = QHostInfo::localHostName();
    QSettings settings(ProductVendor,ProductName);
    settings.beginGroup("Interface");
    designedMode = settings.value("designedMode",true).toBool();
    if (designedMode)
    {
        ui->swTabs->setCurrentIndex(3);
        cContactList = ui->lwContactsDesigned;

        // Change Designed Mode Font size
        QFont designedFont;
        designedFont.setPixelSize(15);
        ui->txtNameDesigned->setFont(designedFont);
        ui->txtPasswordDesigned->setFont(designedFont);
        ui->labDesignedLogin->setFont(designedFont);
        ui->labDesignedLoginDes->setFont(designedFont);
        ui->cbStayLoggedInDesigned->setFont(designedFont);
        ui->cbStartWithWindowsDesigned->setFont(designedFont);

        setWidgetDesign();
    }
    else
    {
        ui->swTabs->setCurrentIndex(0);
        cContactList = ui->lwContacts;
    }
    settings.endGroup();
    settings.beginGroup("Login");
#ifdef WIN32
    this->setMinimumSize(350,450);
    isSWW = settings.value("userBootUp",true).toBool();
    if (!isSWW)
    {
        ui->cbStartWithWindows->setChecked(false);
        ui->cbStartWithWindowsDesigned->setChecked(false);
    }
#elif defined(UNIX)
    this->setMinimumSize(350,450);
    ui->cbStartWithWindows->setVisible(false);
    ui->cbStartWithWindowsDesigned->setVisible(false);
    ui->cbStartWithWindows->setChecked(false);
    ui->cbStartWithWindowsDesigned->setChecked(false);
    isSWW = false;
#else
    this->setMinimumSize(350,450);
    ui->cbStartWithWindows->setVisible(false);
    ui->cbStartWithWindowsDesigned->setVisible(false);
    ui->cbStartWithWindows->setChecked(false);
    ui->cbStartWithWindowsDesigned->setChecked(false);
    isSWW = false;
#endif
    QMenu *cMenu = new QMenu();
    cStateMenu = new QMenu(QApplication::tr("Online status"));
    cStateMenu->setEnabled(false);
    QAction *cOnline = cStateMenu->addAction(QIcon(":/img/online-t2x64.png"),QApplication::tr("Online"));
    connect(cOnline,SIGNAL(triggered()),this,SLOT(setStateOnline()));
    QAction *cAway = cStateMenu->addAction(QIcon(":/img/away-t2x64.png"),QApplication::tr("Away"));
    connect(cAway,SIGNAL(triggered()),this,SLOT(setStateAway()));
    QAction *cBusy = cStateMenu->addAction(QIcon(":/img/busy-t2x64.png"),QApplication::tr("Busy"));
    connect(cBusy,SIGNAL(triggered()),this,SLOT(setStateBusy()));
    QAction *cNotjust = cStateMenu->addAction(QIcon(":/img/notjust-t1x64.png"),QApplication::tr("Not just"));
    connect(cNotjust,SIGNAL(triggered()),this,SLOT(setStateNotjust()));
    QAction *cShowoffline = cStateMenu->addAction(QIcon(":/img/offline-t1x64.png"),QApplication::tr("Show offline"));
    connect(cShowoffline,SIGNAL(triggered()),this,SLOT(setStateShowoffline()));
    cStateMenu->addSeparator();
    QAction *cLogout = cStateMenu->addAction(QApplication::tr("Logout"));
    connect(cLogout,SIGNAL(triggered()),this,SLOT(logoutUserWithRemoveAutologin()));
    cMenu->addMenu(cStateMenu);
    cMenu->addSeparator();
    QAction *cOpen = cMenu->addAction(QIcon(ProductIcon),QApplication::tr("Open KM"));
    connect(cOpen,SIGNAL(triggered()),this,SLOT(openLoginWindowNormal()));
    QAction *cExit = cMenu->addAction(QIcon::fromTheme("application-exit",QIcon(":/gui/close.png")),QApplication::tr("Stop KM"));
    connect(cExit,SIGNAL(triggered()),this,SLOT(endKM()));
    ticon = new QSystemTrayIcon(QIcon(":/img/offline-t1x64.png"));
    ticon->show();
    ticon->setToolTip(QString(ProductName) + " (" + QApplication::tr("Offline") + ")");
    ticon->setContextMenu(cMenu);
    connect(ticon,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),this,SLOT(openLoginWindow(QSystemTrayIcon::ActivationReason)));
    QTimer::singleShot(10,this,SLOT(on_timerLB_tick()));
    QTimer::singleShot(50,this,SLOT(on_timerSS_tick()));
    QTimer::singleShot(25000,this,SLOT(on_timerOA_tick()));
    QTimer::singleShot(10000,this,SLOT(on_timerLC_tick()));
    QTimer::singleShot(207500,this,SLOT(on_timerFR_tick()));
    mouseOverLogin = false;
    mouseOverStatus = false;
    bool autologin = settings.value("Autologin",false).toBool();
    QString autoname = QString::fromUtf8(QByteArray::fromHex(QByteArray::fromBase64(settings.value("Name","").toString().toUtf8())));
    QString autopassword = QString::fromUtf8(QByteArray::fromHex(QByteArray::fromBase64(settings.value("Password","").toString().toUtf8())));
    settings.endGroup();
    isLoggedIn = false;
    isPhonon = false;
    isSayIC = false;
    isSWW = true;
    arWrk = false;
    bigIcon = false;
    fw = new KMsgFw111Q(this);
    connect(fw,SIGNAL(objectIncomed(QString)),this,SLOT(readIncoming(QString)));
    if (autologin)
    {
        ui->txtName->setText(autoname);
        ui->txtNameDesigned->setText(autoname);
        ui->txtPassword->setText(autopassword);
        ui->txtPasswordDesigned->setText(autopassword);
        ui->cbStayLoggedIn->setChecked(true);
        ui->cbStayLoggedIn->setDisabled(true);
        ui->cbStayLoggedInDesigned->setChecked(true);
        ui->cbStayLoggedInDesigned->setDisabled(true);
        ui->txtName->setDisabled(true);
        ui->txtPassword->setDisabled(true);
        ui->cmdLogin->setDisabled(true);
        QTimer::singleShot(50,this,SLOT(on_doAutologin()));
    }
    settings.beginGroup("Windows");
    if (settings.contains("loginGeometry") && settings.contains("loginState"))
    {
        restoreGeometry(settings.value("loginGeometry").toByteArray());
        restoreState(settings.value("loginState").toByteArray());
    }
    settings.endGroup();
}

frmLogin::~frmLogin()
{
    delete ui;
#ifdef UPDATE_MANAGER
    ut->terminate();
#endif
    qApp->exit(0);
}

void frmLogin::setWidgetDesign()
{
#ifdef QT4
    QStyle *KMStyle = QStyleFactory::create("cleanlooks");
#else
#ifdef QT5
    QStyle *KMStyle = QStyleFactory::create("fusion");
#else
    QCommonStyle *KMStyle = new QCommonStyle();
#endif
#endif
    ui->labDesignedLogin->setStyle(KMStyle);
    ui->frContactsSearch->setStyle(KMStyle);
    ui->frContactsSearch->setMinimumSize(0,20);
    ui->frStatus->setStyle(KMStyle);
    QStyle *TStyle = QStyleFactory::create(qApp->style()->objectName());
    ui->txtContactsSearch->setStyle(TStyle);

    foreach(QObject *object, stringLinkChat.values())
    {
        frmChat* cw = (frmChat*)object;
        cw->setWidgetDesign();
    }
}

void frmLogin::on_doAutologin()
{
    ui->cbStayLoggedIn->setEnabled(true);
    ui->cbStayLoggedInDesigned->setEnabled(true);
    ui->txtName->setEnabled(true);
    ui->txtPassword->setEnabled(true);
    ui->cmdLogin->setEnabled(true);
    loginUserDataFromLines(false, true);
}

void frmLogin::setStateOnline()
{
    if (isConnectedWithServer())
    {
        fw->setUserOnlineState(1);
        fw->requestGetUserOnlineState();
    }
    else
    {
        QMessageBox::information(this,QApplication::tr("Offline"),QApplication::tr("You are offline, please wait until you're online!"));
    }
}

void frmLogin::setStateAway()
{
    if (isConnectedWithServer())
    {
        fw->setUserOnlineState(2);
        fw->requestGetUserOnlineState();
    }
    else
    {
        QMessageBox::information(this,QApplication::tr("Offline"),QApplication::tr("You are offline, please wait until you're online!"));
    }
}

void frmLogin::setStateBusy()
{
    if (isConnectedWithServer())
    {
        fw->setUserOnlineState(3);
        fw->requestGetUserOnlineState();
    }
    else
    {
        QMessageBox::information(this,QApplication::tr("Offline"),QApplication::tr("You are offline, please wait until you're online!"));
    }
}

void frmLogin::setStateNotjust()
{
    if (isConnectedWithServer())
    {
        fw->setUserOnlineState(4);
        fw->requestGetUserOnlineState();
    }
    else
    {
        QMessageBox::information(this,QApplication::tr("Offline"),QApplication::tr("You are offline, please wait until you're online!"));
    }
}

void frmLogin::setStateShowoffline()
{
    if (isConnectedWithServer())
    {
        fw->setUserOnlineState(5);
        fw->requestGetUserOnlineState();
    }
    else
    {
        QMessageBox::information(this,QApplication::tr("Offline"),QApplication::tr("You are offline, please wait until you're online!"));
    }
}

void frmLogin::changePassword()
{
    if (isConnectedWithServer())
    {
        frmChangePassword *cp = new frmChangePassword(this);
        cp->setForm(this);
        cp->setWindowIcon(QIcon(ProductIcon));
        cp->show();
        cp->exec();
        cp->deleteLater();
        delete cp;
    }
    else
    {
        QMessageBox::information(this,QApplication::tr("Offline"),QApplication::tr("You are offline, please wait until you're online!"));
    }
}

void frmLogin::editProfile()
{
    on_labWelcomeNick_linkActivated("kmp://editprofile");
}

void frmLogin::logoutUserWithRemoveAutologin()
{
    QSettings settings(ProductVendor,ProductName);
    settings.beginGroup("Login");
    settings.setValue("Autologin",false);
    settings.remove("Name");
    settings.remove("Password");
#ifdef WIN32
    QSettings userBootUp("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat);
    userBootUp.remove(ProductName);
    settings.setValue("userBootUp",false);
#endif
    settings.endGroup();
    logoutUser();
}

void frmLogin::logoutUser()
{
    fw->logoutUser();
    isLoggedIn = false;
    ui->txtName->clear();
    ui->txtNameDesigned->clear();
    if (designedMode)
    {
        ui->txtNameDesigned->setFocus();
    }
    else
    {
        ui->txtName->setFocus();
    }
    ui->txtPassword->clear();
    ui->txtPasswordDesigned->clear();
    ui->cbStayLoggedIn->setChecked(true);
    ui->cbStayLoggedInDesigned->setChecked(true);
    ui->cbStartWithWindows->setChecked(isSWW);
    ui->cbStartWithWindowsDesigned->setChecked(isSWW);
    if (designedMode)
    {
        ui->swTabs->setCurrentIndex(3);
    }
    else
    {
        ui->swTabs->setCurrentIndex(0);
    }
    ui->lwContacts->clear();
    ui->lwContactsDesigned->clear();
    stringLinkContact.clear();
    contactLinkString.clear();
    stringLinkBool.clear();
    stringLinkNick.clear();
    stringLinkImage.clear();
    stringLinkAvatar.clear();
    stringLinkOnlineState.clear();
    stringLinkPixmapState.clear();
    stringLinkMessageState.clear();
    stringLinkAction.clear();
    menu_Away->deleteLater();
    menu_Busy->deleteLater();
    menu_AddContact->deleteLater();
    menu_ChangePassword->deleteLater();
    menu_EditProfile->deleteLater();
    menu_ServerGroupChat->deleteLater();
    menu_Close->deleteLater();
    menu_Logout->deleteLater();
    menu_M1Seperator->deleteLater();
    menu_M2Seperator->deleteLater();
    menu_Messenger->deleteLater();
    menu_Notjust->deleteLater();
    menu_Online->deleteLater();
    menu_Onlinestatus->deleteLater();
    menu_Showoffline->deleteLater();
    menu_Tools->deleteLater();
    destroyLanguages();
    menu_Languages->deleteLater();
    menu_Config->deleteLater();
    menu_Help->deleteLater();
#ifdef UPDATE_MANAGER
    menu_CheckUpdate->deleteLater();
    menu_HUSeperator->deleteLater();
#endif
    menu_AboutKeppe->deleteLater();
    menu_AboutKMP->deleteLater();
#ifndef MACX
    ui->menuBar->setHidden(true);
#endif
    ticon->setIcon(QIcon(getIconPathForTaskBarOnlineState(8)));
    ticon->setToolTip(QString(ProductName) + " (" + getTaskBarOnlineStateStringFromID(8) + ")");
    ui->labUserStatusDesigned->setPixmap(QPixmap(getIconPathForTaskBarOnlineState(8)));
    foreach(QObject *object, stringLinkChat.values())
    {
        frmChat* cw = (frmChat*)object;
        cw->close();
    }
    stringLinkChat.clear();
}

void frmLogin::loginUserDataFromLines(bool showErrors, bool ignoreFailedConnection)
{
    int ret = fw->loginUser(ui->txtName->text(),ui->txtPassword->text());
    if (ret == 200)
    {
        if (ui->cbStayLoggedIn->isChecked() && ui->cbStartWithWindows->isChecked())
        {
            QSettings settings(ProductVendor,ProductName);
            settings.beginGroup("Login");
            settings.setValue("Autologin",true);
            settings.setValue("Name",QString::fromUtf8(ui->txtName->text().toUtf8().toHex().toBase64()));
            settings.setValue("Password",QString::fromUtf8(ui->txtPassword->text().toUtf8().toHex().toBase64()));
#ifdef WIN32
            QSettings userBootUp("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat);
            userBootUp.setValue(ProductName,"\"" + qApp->applicationFilePath().replace("/","\\") + "\" --minimized");
            settings.setValue("userBootUp",true);
#endif
            settings.endGroup();
        }
        else if (ui->cbStayLoggedIn->isChecked())
        {
            QSettings settings(ProductVendor,ProductName);
            settings.beginGroup("Login");
            settings.setValue("Autologin",true);
            settings.setValue("Name",QString::fromUtf8(ui->txtName->text().toUtf8().toHex().toBase64()));
            settings.setValue("Password",QString::fromUtf8(ui->txtPassword->text().toUtf8().toHex().toBase64()));
#ifdef WIN32
            QSettings userBootUp("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat);
            userBootUp.remove(ProductName);
            settings.setValue("userBootUp",false);
#endif
            settings.endGroup();
        }
        else
        {
            QSettings settings(ProductVendor,ProductName);
            settings.beginGroup("Login");
            settings.setValue("Autologin",false);
            settings.remove("Name");
            settings.remove("Password");
            settings.endGroup();
        }
        isLoggedIn = true;
        if (designedMode)
        {
            ui->swTabs->setCurrentIndex(4);
            cContactList->setFocus();
        }
        else
        {
            ui->swTabs->setCurrentIndex(1);
            cContactList->setFocus();
        }
        myNickname = QString(fw->getUserNick());
        if (myNickname.left(8) == "///Error")
        {
            myNickname = ui->txtName->text();
        }
        updateWelcomeLabel(myNickname);
        fw->requestGetUserAvatar();
        fw->requestGetUserContactsWithAvatar();
        fw->requestGetUserContactsWithStates();
        updateFriendRequests();
        fw->requestGetUserOnlineState();
        setupMenu();
    }
    else if (ret == 404)
    {
        if (showErrors) {QMessageBox::warning(this,QApplication::tr("Login"),QApplication::tr("You have type invalid account data!"));}
    }
    else if (ret == 500)
    {
        if (showErrors) {QMessageBox::warning(this,QApplication::tr("Login"),QApplication::tr("Can't connect to %1 Server").arg(ProductName));}
        if (ignoreFailedConnection)
        {
            if (ui->cbStayLoggedIn->isChecked() && ui->cbStartWithWindows->isChecked())
            {
                QSettings settings(ProductVendor,ProductName);
                settings.beginGroup("Login");
                settings.setValue("Autologin",true);
                settings.setValue("Name",QString::fromUtf8(ui->txtName->text().toUtf8().toHex().toBase64()));
                settings.setValue("Password",QString::fromUtf8(ui->txtPassword->text().toUtf8().toHex().toBase64()));
#ifdef WIN32
                QSettings userBootUp("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat);
                userBootUp.setValue(ProductName,"\"" + qApp->applicationFilePath().replace("/","\\") + "\" --minimized");
                settings.setValue("userBootUp",true);
#endif
                settings.endGroup();
            }
            else if (ui->cbStayLoggedIn->isChecked())
            {
                QSettings settings(ProductVendor,ProductName);
                settings.beginGroup("Login");
                settings.setValue("Autologin",true);
                settings.setValue("Name",QString::fromUtf8(ui->txtName->text().toUtf8().toHex().toBase64()));
                settings.setValue("Password",QString::fromUtf8(ui->txtPassword->text().toUtf8().toHex().toBase64()));
#ifdef WIN32
                QSettings userBootUp("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat);
                userBootUp.remove(ProductName);
                settings.setValue("userBootUp",false);
#endif
                settings.endGroup();
            }
            else
            {
                QSettings settings(ProductVendor,ProductName);
                settings.beginGroup("Login");
                settings.setValue("Autologin",false);
                settings.remove("Name");
                settings.remove("Password");
                settings.endGroup();
            }
            QSettings settings(ProductVendor,ProductName);
            settings.beginGroup("Nick");
            QString nickname = settings.value(ui->txtName->text(),ui->txtName->text()).toString();
            settings.endGroup();
            setupMessenger(8, nickname);
        }
    }
}

void frmLogin::setupMenu()
{
    menu_Messenger = ui->menuBar->addMenu(QApplication::tr("Messenger"));
    menu_Onlinestatus = menu_Messenger->addMenu(QApplication::tr("Online status"));
    menu_Online = menu_Onlinestatus->addAction(QIcon(":/img/online-t2x64.png"),QApplication::tr("Online"),this,SLOT(setStateOnline()));
    menu_Away = menu_Onlinestatus->addAction(QIcon(":/img/away-t2x64.png"),QApplication::tr("Away"),this,SLOT(setStateAway()));
    menu_Busy = menu_Onlinestatus->addAction(QIcon(":/img/busy-t2x64.png"),QApplication::tr("Busy"),this,SLOT(setStateBusy()));
    menu_Notjust = menu_Onlinestatus->addAction(QIcon(":/img/notjust-t1x64.png"),QApplication::tr("Not just"),this,SLOT(setStateNotjust()));
    menu_Showoffline = menu_Onlinestatus->addAction(QIcon(":/img/offline-t1x64.png"),QApplication::tr("Show offline"),this,SLOT(setStateShowoffline()));
    menu_M1Seperator = menu_Messenger->addSeparator();
    menu_AddContact = menu_Messenger->addAction(QApplication::tr("Add contact"),this,SLOT(addContact()));
    menu_ChangePassword = menu_Messenger->addAction(QApplication::tr("Change password"),this,SLOT(changePassword()));
    menu_EditProfile = menu_Messenger->addAction(QApplication::tr("Edit profile"),this,SLOT(editProfile()));
    menu_M2Seperator = menu_Messenger->addSeparator();
    menu_Logout = menu_Messenger->addAction(QApplication::tr("Logout"),this,SLOT(logoutUserWithRemoveAutologin()));
    menu_Logout->setShortcut(QKeySequence::fromString("CTRL+L"));
    menu_Close = menu_Messenger->addAction(QApplication::tr("Close"),this,SLOT(showMinimized()));
    menu_Close->setShortcut(QKeySequence::fromString("ALT+F4"));
    menu_Tools = ui->menuBar->addMenu(QApplication::tr("Tools"));
    menu_Languages = menu_Tools->addMenu(QApplication::tr("Change Language"));
    setupLanguages();
    menu_A1Seperator = menu_Tools->addSeparator();
#ifdef MACX
    menu_Config = menu_Tools->addAction("Preferences",this,SLOT(openConfig()));
    menu_Config->setShortcut(QKeySequence::fromString("CTRL+S"));
#else
    menu_Config = menu_Tools->addAction(QApplication::tr("Preferences"),this,SLOT(openConfig()));
    menu_Config->setShortcut(QKeySequence::fromString("CTRL+S"));
#endif
    menu_Help = ui->menuBar->addMenu(QApplication::tr("Help"));
#ifdef UPDATE_MANAGER
    menu_CheckUpdate = menu_Help->addAction(QApplication::tr("Check for Update"),this,SLOT(checkUpdate()));
    menu_CheckUpdate->setShortcut(QKeySequence::fromString("CTRL+U"));
    menu_HUSeperator = menu_Help->addSeparator();
#endif
#ifdef MACX
    menu_AboutKMP = menu_Help->addAction(QIcon(ProductIcon),"About",this,SLOT(aboutKMP()));
    menu_AboutKMP->setShortcut(QKeySequence::fromString("CTRL+A"));
    menu_AboutKeppe = menu_Help->addAction(QIcon(VendorIcon),QApplication::tr("About %1").arg(ProductVendor),this,SLOT(aboutKeppe()));
    menu_AboutKeppe->setShortcut(QKeySequence::fromString("CTRL+K"));
#else
    menu_AboutKeppe = menu_Help->addAction(QIcon(VendorIcon),QApplication::tr("About %1").arg(ProductVendor),this,SLOT(aboutKeppe()));
    menu_AboutKeppe->setShortcut(QKeySequence::fromString("CTRL+V"));
    menu_AboutKMP = menu_Help->addAction(QIcon(ProductIcon),QApplication::tr("About %1").arg(ProductItl),this,SLOT(aboutKMP()));
    menu_AboutKMP->setShortcut(QKeySequence::fromString("CTRL+A"));
#endif
#ifndef MACX
    ui->menuBar->setHidden(false);
#endif
}

void frmLogin::destroyLanguages()
{
    langWrapper.clear();
    foreach(const QString &key,stringLinkAction.keys())
    {
        stringLinkAction[key]->deleteLater();
        stringLinkAction.remove(key);
    }
}

void frmLogin::setupLanguages()
{
    langWrapper["System"] = "System";
    QAction *systemAction = menu_Languages->addAction("System (System)");
    connect(systemAction,SIGNAL(triggered()),SLOT(setLanguage()));
    stringLinkAction["System"] = systemAction;
    langWrapper["English"] = "en";
    langWrapper["en"] = "English";
    QAction *englishAction = menu_Languages->addAction("English (English)");
    if (QFile::exists(QString(":/tr/us.png")))
    {
        englishAction->setIcon(QIcon::fromTheme("flag-us",QIcon(":/tr/us.png")));
    }
    connect(englishAction,SIGNAL(triggered()),SLOT(setLanguage()));
    stringLinkAction["en"] = englishAction;
    QDir trDir;
    trDir.cd(":/tr");
    foreach(const QString& key, trDir.entryList(putStringToStringList("km_*.qm")))
    {
        qDebug() << QString("Language " + key + " found").toStdString().c_str();
        QTranslator trFile;
        bool ok = trFile.load(QString(":/tr/" + key));
        if (ok)
        {
            qDebug() << QString("Language " + key + " loaded").toStdString().c_str();
            QString trName = key;
            trName = trName.remove("km_").remove(".qm");
            QLocale trLocale(trName);
#if QT_VERSION >= 0x040800
            QString trNative = trLocale.nativeLanguageName();
#else
            QString trNative = QLocale::languageToString(trLocale.language());
#endif
            QString trInter = QLocale::languageToString(trLocale.language());
            if (trNative != "")
            {
                qDebug() << QString("Language " + key + " detected as " + trNative + " (" + trInter + ")").toStdString().c_str();
                langWrapper[trName] = trNative;
                langWrapper[trNative] = trName;
                QAction *langAction = menu_Languages->addAction(trNative + " (" + trInter + ")");
                if (QFile::exists(QString(":/tr/" + trName + ".png")))
                {
                    langAction->setIcon(QIcon::fromTheme("flag-" + trName,QIcon(":/tr/" + trName + ".png")));
                }
                connect(langAction,SIGNAL(triggered()),SLOT(setLanguage()));
                stringLinkAction[trName] = langAction;
                qDebug() << QString("Language " + key + " added").toStdString().c_str();
            }
            else
            {
                qDebug() << QString("Language " + key + " not detected and add failed").toStdString().c_str();
            }
        }
        else
        {
            qDebug() << QString("Language " + key + " load failed").toStdString().c_str();
        }
    }
    QDir trPlugsDir;
    trPlugsDir.cd(languagePath);
    foreach(const QString& key, trPlugsDir.entryList(putStringToStringList("km_*.qm")))
    {
        qDebug() << QString("Language " + key + " found").toStdString().c_str();
        QTranslator trFile;
        bool ok = trFile.load(QString(languagePath + "/" + key));
        if (ok)
        {
            qDebug() << QString("Language " + key + " loaded").toStdString().c_str();
            QString trName = key;
            trName = trName.remove("km_").remove(".qm");
            QLocale trLocale(trName);
#if QT_VERSION >= 0x040800
            QString trNative = trLocale.nativeLanguageName();
#else
            QString trNative = QLocale::languageToString(trLocale.language());
#endif
            QString trInter = QLocale::languageToString(trLocale.language());
            if (trNative != "")
            {
                qDebug() << QString("Language " + key + " detected as " + trNative + " (" + trInter + ")").toStdString().c_str();
                langWrapper[trName] = trNative;
                langWrapper[trNative] = trName;
                QAction *langAction = menu_Languages->addAction(trNative + " (" + trInter + ")");
                if (QFile::exists(QString(":/tr/" + trName + ".png")))
                {
                    langAction->setIcon(QIcon::fromTheme("flag-" + trName,QIcon(":/tr/" + trName + ".png")));
                }
                connect(langAction,SIGNAL(triggered()),SLOT(setLanguage()));
                stringLinkAction[trName] = langAction;
                qDebug() << QString("Language " + key + " added").toStdString().c_str();
            }
            else
            {
                qDebug() << QString("Language " + key + " not detected and add failed").toStdString().c_str();
            }
        }
        else
        {
            qDebug() << QString("Language " + key + " load failed").toStdString().c_str();
        }
    }
}

void frmLogin::setLanguage()
{
    QAction *action = (QAction*)sender();
    QString key = stringLinkAction.key(action);

    QSettings settings(ProductVendor,ProductName);
    settings.beginGroup("Interface");
    settings.setValue("Language",key);
    settings.endGroup();

    QProcess *newMessenger = new QProcess;
    newMessenger->startDetached("\"" + qApp->applicationFilePath() + "\"");
    newMessenger->deleteLater();
    delete newMessenger;
    ticon->deleteLater();
    delete ticon;
    qApp->exit(0);
}

void frmLogin::setupMessenger(int onlineState, QString nickname)
{
    isLoggedIn = true;
    isSayIC = true;
    if (designedMode)
    {
        ui->swTabs->setCurrentIndex(4);
        cContactList->setFocus();
    }
    else
    {
        ui->swTabs->setCurrentIndex(1);
        cContactList->setFocus();
    }
    myNickname = nickname;
    updateWelcomeLabel(myNickname);
    ticon->setIcon(QIcon(getIconPathForTaskBarOnlineState(onlineState)));
    ticon->setToolTip(QString(ProductName) + " (" + getTaskBarOnlineStateStringFromID(onlineState) + ")");
    ui->labUserStatusDesigned->setPixmap(QPixmap(getIconPathForTaskBarOnlineState(onlineState)));
    setupMenu();
}

void frmLogin::aboutKeppe()
{
    frmAboutKeppe *ak = new frmAboutKeppe(this);
    ak->setWindowIcon(QIcon(ProductIcon));
    ak->show();
    ak->exec();
    ak->deleteLater();
    delete ak;
}

void frmLogin::aboutKMP()
{
    frmAboutKMPQ *am = new frmAboutKMPQ(this);
    am->setForm(this);
    am->setWindowIcon(QIcon(ProductIcon));
    am->setWindowTitle(QApplication::tr("About %1").arg(QString(ProductName) + " (" + QString(ProductItl) + ")"));
    am->updateText();
    am->show();
    am->exec();
    am->deleteLater();
    delete am;
}

void frmLogin::openConfig()
{
    frmConfig *cw = new frmConfig(this,languagePath);
    cw->setForm(this);
    cw->setWindowIcon(QIcon(ProductIcon));
    cw->show();
    cw->exec();
    cw->deleteLater();
    delete cw;
}

void frmLogin::openLoginWindowNormal()
{
    this->showNormal();
    this->activateWindow();
}

void frmLogin::openLoginWindow(QSystemTrayIcon::ActivationReason reason)
{
    if (reason == QSystemTrayIcon::DoubleClick)
    {
        if (this->isMinimized())
        {
            this->showNormal();
            this->activateWindow();
        }
        else
        {
            this->showMinimized();
        }
    }
}

void frmLogin::closeEvent(QCloseEvent *event)
{
    if (isLoggedIn)
    {
        this->showMinimized();
        event->ignore();
    }
    else
    {
        ticon->deleteLater();
        delete ticon;
        QSettings settings(ProductVendor,ProductName);
        settings.beginGroup("Windows");
        settings.setValue("loginGeometry", saveGeometry());
        settings.setValue("loginState", saveState());
        settings.endGroup();
        event->accept();
        qApp->exit(0);
    }
}

void frmLogin::endKM()
{
    if (isLoggedIn)
    {
        logoutUser();
    }
    this->close();
}

QString frmLogin::getIconPathForOnlineState(int id)
{
    if (id == 1)
    {
        return ":/img/online-t2x64.png";
    }
    if (id == 2)
    {
        return ":/img/away-t2x64.png";
    }
    if (id == 3)
    {
        return ":/img/busy-t2x64.png";
    }
    if (id == 4)
    {
        return ":/img/notjust-t1x64.png";
    }
    if (id == 5)
    {
        return ":/img/showoffline-t1x64.png";
    }
    if (id == 8)
    {
        return ":/img/offline-t1x64.png";
    }
    return ":/img/offline-t1x64.png";
}

QString frmLogin::getIconPathForTaskBarOnlineState(int id)
{
    if (id == 1)
    {
        return ":/img/online-t2x64.png";
    }
    if (id == 2)
    {
        return ":/img/away-t2x64.png";
    }
    if (id == 3)
    {
        return ":/img/busy-t2x64.png";
    }
    if (id == 4)
    {
        return ":/img/notjust-t1x64.png";
    }
    if (id == 5)
    {
        return ":/img/offline-t1x64.png";
    }
    if (id == 8)
    {
        return ":/img/offline-t1x64.png";
    }
    return ":/img/offline-t1x64.png";
}

QString frmLogin::getPixmapPathForNotificationOnlineState(int id)
{
    if (id == 1)
    {
        return ":/img/notification-online.png";
    }
    if (id == 2)
    {
        return ":/img/notification-away.png";
    }
    if (id == 3)
    {
        return ":/img/notification-busy.png";
    }
    if (id == 4)
    {
        return ":/img/notification-notjust.png";
    }
    if (id == 5)
    {
        return ":/img/notification-showoffline.png";
    }
    if (id == 8)
    {
        return ":/img/notification-offline.png";
    }
    return ":/img/notification-offline.png";
}

QString frmLogin::getTaskBarOnlineStateStringFromID(int id)
{
    if (id == 1)
    {
        return QApplication::tr("Online");
    }
    if (id == 2)
    {
        return QApplication::tr("Away");
    }
    if (id == 3)
    {
        return QApplication::tr("Busy");
    }
    if (id == 4)
    {
        return QApplication::tr("Not just");
    }
    if (id == 5)
    {
        return QApplication::tr("Show offline");
    }
    if (id == 8)
    {
        return QApplication::tr("Offline");
    }
    return QApplication::tr("Offline");
}

void frmLogin::on_timerFR_tick()
{
    if (isLoggedIn)
    {
        if (fw->isLoggedIn())
        {
            updateFriendRequests();
            fw->requestGetUserAvatar();
        }
    }
    QTimer::singleShot(207500,this,SLOT(on_timerFR_tick()));
}

void frmLogin::on_timerSS_tick()
{
    if (isLoggedIn)
    {
        if (fw->isLoggedIn())
        {
            if (!cStateMenu->isEnabled()) {cStateMenu->setEnabled(true);}
            if (fw->isObjectIncoming())
            {
                QString readstr = fw->readObject();
                readIncoming(readstr);
            }
        }
    }
    QTimer::singleShot(100,this,SLOT(on_timerSS_tick()));
}

void frmLogin::on_timerLB_tick()
{
    if (ui->labDesignedLogin->rect().contains(ui->labDesignedLogin->mapFromGlobal(QCursor::pos())))
    {
        if (!mouseOverLogin)
        {
            ui->labDesignedLogin->setStyleSheet("background-color: rgb(255, 255, 255); border-color: rgb(215, 120, 50); color: rgb(215, 70, 25);");
        }
        mouseOverLogin = true;
    }
    else
    {
        if (mouseOverLogin)
        {
            ui->labDesignedLogin->setStyleSheet("background-color: rgb(215, 70, 25); border-color: rgb(215, 120, 50);");
        }
        mouseOverLogin = false;
    }
    if (ui->frStatus->rect().contains(ui->frStatus->mapFromGlobal(QCursor::pos())))
    {
        if (!mouseOverStatus)
        {
            ui->frStatus->setStyleSheet("background-color: rgb(191, 191, 191); color: rgb(255, 255, 255);");
        }
        mouseOverStatus = true;
    }
    else
    {
        if (mouseOverStatus)
        {
            ui->frStatus->setStyleSheet("background-color: rgb(255, 255, 255); color: rgb(128, 128, 128);");
        }
        mouseOverStatus = false;
    }
    QTimer::singleShot(10,this,SLOT(on_timerLB_tick()));
}

void frmLogin::readIncoming(QString readstr)
{
    if (readstr != "")
    {
        QStringList readstrlist = readstr.split("<>");
        if (readstrlist.length() >= 1)
        {
            if (readstrlist.at(0) == "MessageFromUser")
            {
                qDebug() << "Go to MessageFromUser mode";
                if (readstrlist.length() >= 2)
                {
                    QStringList msg = readstrlist.at(1).split(":");
                    QString username;
                    if (msg.length() >= 1)
                    {
                        username = msg.at(0);
                    }
                    QString message;
                    int len = 17+username.length()+1;
                    if (readstr.length() >= len)
                    {
                        message = readstr.remove(0,len);
                    }
                    message = message.trimmed();
                    if (username.trimmed() == "" || message.trimmed() == "")
                    {
                        //Error
                    }
                    else
                    {
                        if (!stringLinkChat.contains(username))
                        {
                            if (stringLinkNick.contains(username) && stringLinkMessageState.contains(username))
                            {
                                if (stringLinkAvatar.contains(username))
                                {
                                    openChatWindow(username,getCustomNick(username),stringLinkMessageState[username],stringLinkPixmapState[username],stringLinkOnlineState[username],stringLinkAvatar[username],true);
                                }
                                else
                                {
                                    openChatWindow(username,getCustomNick(username),stringLinkMessageState[username],stringLinkPixmapState[username],stringLinkOnlineState[username],"",true);
                                }
                            }
                            else
                            {
                                openChatWindow(username,getCustomNick(username),QApplication::tr("<span style=\"color: blue;\">%1</span><span> is not in your contacts!</span>").arg(getCustomNick(username)),getIconPathForOnlineState(8),8,"",true);
                            }
                            playChatIn();
                        }
                        frmChat *cw = (frmChat*)stringLinkChat[username];
                        if (!cw->isActiveWindow() || cw->isMinimized())
                        {
                            QByteArray notificationPreMessage = fromMessage(message);
                            if (notificationPreMessage.length() > 25)
                            {
                                notificationPreMessage = notificationPreMessage.left(23) + "..";
                            }
                            QString notificationMessage = cw->convertMessage(toNotificationMessage(notificationPreMessage));
                            showNotification("<span style=\"color: blue;\">" + getCustomNick(username) + "</span><br>" + notificationMessage,QApplication::tr("Incoming Message"),"ocw\n" + username,true,QPixmap(":/img/notification-mail.png"));
                            playChatIn();
                        }
                        cw->incomingMessage(message);
                        if (cw->isMinimized())
                        {
                            cw->activateWindow();
                        }
                    }
                }
            }
            else if (readstrlist.at(0) == "ReturnIntialize")
            {
                qDebug() << "Go to ReturnIntialize mode";
                int id = 500;
                int state = 500;
                QString users;
                QString action;
                QString avatar;
                QString request;
                QString username;
                QString notification;
                foreach(QString argstr,readstrlist)
                {
                    if (argstr.left(5) == "--at=")
                    {
                        action = argstr.remove(0,5).replace("&nbsp;"," ").replace("&amp;","&");
                    }
                    if (argstr.left(5) == "--rq=")
                    {
                        request = argstr.remove(0,5).replace("&nbsp;"," ").replace("&amp;","&");
                    }
                    if (argstr.left(5) == "--nt=")
                    {
                        notification = argstr.remove(0,5).replace("&nbsp;"," ").replace("&amp;","&");
                    }
                    if (argstr.left(5) == "--id=")
                    {
                        id = QVariant(argstr.remove(0,5)).toInt();
                    }
                    if (argstr.left(8) == "--state=")
                    {
                        state = QVariant(argstr.remove(0,8)).toInt();
                    }
                    if (argstr.left(8) == "--users=")
                    {
                        users = argstr.remove(0,8).replace("&nbsp;"," ").replace("&amp;","&").replace("&lt;&gt;","\n");
                    }
                    if (argstr.left(9) == "--avatar=")
                    {
                        avatar = argstr.remove(0,9).replace("&nbsp;"," ").replace("&amp;","&").replace("&lt;&gt;","\n");
                    }
                    if (argstr.left(11) == "--username=")
                    {
                        username = argstr.remove(0,11).replace("&nbsp;"," ").replace("&amp;","&").replace("&lt;&gt;","\n");
                    }
                }
                if (request == "avatar" && id == 200)
                {
                    qDebug() << "Avatar sended";
                    stringLinkAvatar[ui->txtName->text()] = avatar;
                    arList.append(avatar);
                    arList.removeDuplicates();
                    if (!arWrk)
                    {
                        at = new AvatarThread(arList,stringLinkImage.keys());
                        connect(at,SIGNAL(avatarInsert(QByteArray,QString)),this,SLOT(avatarInsert(QByteArray,QString)));
                        connect(at,SIGNAL(finished()),this,SLOT(setAvatarWorkFalse()));
                        at->start(QThread::LowPriority);
                        arWrk = true;
                    }
                }
                else if (request == "contactswithstates" && id == 200)
                {
                    qDebug() << "Contacts with states list sended";
                    QString contactsString = users;
                    QStringList contactList = contactsString.split("\n");
                    contactList.removeAll("");
                    contactList.removeAll("\r");
                    contactList.removeAll("\n");
                    contactList.removeAll("\r\n");
                    if (contactList.length() >= 1)
                    {
                        foreach (const QString &contact,contactList)
                        {
                            QStringList contactQIL = contact.split("|");
                            if (contactQIL.length() >= 4)
                            {
                                QSettings settings(ProductVendor,ProductName);
                                settings.beginGroup("Nick");
                                settings.setValue(contactQIL.at(0),contactQIL.at(1));
                                settings.endGroup();
                                if (stringLinkContact.contains(contactQIL.at(0)))
                                {

                                    QListWidgetItem *contactItem = stringLinkContact[contactQIL.at(0)];
                                    int contactState = QVariant(contactQIL.at(3)).toInt();
                                    int oldState = stringLinkOnlineState[contactQIL.at(0)];
                                    contactItem->setText(getCustomNick(contactQIL.at(0)) + "\n" + QString::fromUtf8(fromMessage(contactQIL.at(2))));
                                    stringLinkNick[contactQIL.at(0)] = contactQIL.at(1);
                                    stringLinkOnlineState[contactQIL.at(0)] = contactState;
                                    stringLinkPixmapState[contactQIL.at(0)] = getIconPathForOnlineState(contactState);
                                    stringLinkMessageState[contactQIL.at(0)] = contactQIL.at(2);
                                    if (!stringLinkAvatar.contains(contactQIL.at(0)))
                                    {
                                        stringLinkAvatar[contactQIL.at(0)] = "";
                                    }
                                    if (oldState != contactState)
                                    {
                                        contactItem->setIcon(generateContactIcon(getAvatarImage(stringLinkAvatar[contactQIL.at(0)]),QImage(getIconPathForOnlineState(contactState))));
                                    }
                                    else
                                    {
                                        if (stringLinkBool.contains(contactQIL.at(0)))
                                        {
                                            if (!stringLinkBool[contactQIL.at(0)])
                                            {
                                                contactItem->setIcon(generateContactIcon(getAvatarImage(stringLinkAvatar[contactQIL.at(0)]),QImage(getIconPathForOnlineState(contactState))));
                                            }
                                        }
                                        else
                                        {
                                            contactItem->setIcon(generateContactIcon(getAvatarImage(stringLinkAvatar[contactQIL.at(0)]),QImage(getIconPathForOnlineState(contactState))));
                                        }
                                    }
                                    if (stringLinkChat.contains(contactQIL.at(0)))
                                    {
                                        frmChat *cw = (frmChat*)stringLinkChat[contactQIL.at(0)];
                                        cw->setChatter(contactQIL.at(0),getCustomNick(contactQIL.at(0)),contactQIL.at(2),myNickname,getIconPathForOnlineState(contactState),contactState,stringLinkAvatar[contactQIL.at(0)]);
                                    }
                                }
                                else
                                {
                                    QListWidgetItem *contactItem = new QListWidgetItem(getCustomNick(contactQIL.at(0)) + "\n" + QString::fromUtf8(fromMessage(contactQIL.at(2))));
                                    int contactState = QVariant(contactQIL.at(3)).toInt();
                                    stringLinkContact[contactQIL.at(0)] = contactItem;
                                    stringLinkNick[contactQIL.at(0)] = contactQIL.at(1);
                                    stringLinkOnlineState[contactQIL.at(0)] = contactState;
                                    stringLinkPixmapState[contactQIL.at(0)] = getIconPathForOnlineState(contactState);
                                    stringLinkMessageState[contactQIL.at(0)] = contactQIL.at(2);
                                    if (!stringLinkAvatar.contains(contactQIL.at(0)))
                                    {
                                        stringLinkAvatar[contactQIL.at(0)] = "";
                                    }
                                    contactItem->setIcon(generateContactIcon(getAvatarImage(stringLinkAvatar[contactQIL.at(0)]),QImage(getIconPathForOnlineState(contactState))));
                                    contactLinkString[contactItem] = contactQIL.at(0);
                                    cContactList->addItem(contactItem);
                                    if (stringLinkChat.contains(contactQIL.at(0)))
                                    {
                                        frmChat *cw = (frmChat*)stringLinkChat[contactQIL.at(0)];
                                        cw->setChatter(contactQIL.at(0),getCustomNick(contactQIL.at(0)),contactQIL.at(2),myNickname,getIconPathForOnlineState(contactState),contactState,stringLinkAvatar[contactQIL.at(0)]);
                                    }
                                }
                            }
                        }
                    }
                }
                else if (request == "contactswithavatar" && id == 200)
                {
                    qDebug() << "Contacts with avatar list sended";
                    QString contactsString = users;
                    QStringList contactList = contactsString.split("\n");
                    contactList.removeAll("");
                    contactList.removeAll("\r");
                    contactList.removeAll("\n");
                    contactList.removeAll("\r\n");
                    if (contactList.length() >= 1)
                    {
                        foreach (const QString &contact,contactList)
                        {
                            QStringList contactQIL = contact.split("|");
                            if (contactQIL.length() >= 2)
                            {
                                if (stringLinkAvatar.contains(contactQIL.at(0)))
                                {
                                    if (stringLinkAvatar[contactQIL.at(0)] == contactQIL.at(1))
                                    {
                                        if (!stringLinkImage.contains(contactQIL.at(1)))
                                        {
                                            stringLinkBool[contactQIL.at(0)] = false;
                                            stringLinkAvatar[contactQIL.at(0)] = "";
                                            arList.append(contactQIL.at(1));
                                        }
                                        else
                                        {
                                            if (!stringLinkBool[contactQIL.at(0)])
                                            {
                                                int onlineState = 8;
                                                if (stringLinkOnlineState.contains(contactQIL.at(0)))
                                                {
                                                    onlineState = stringLinkOnlineState[contactQIL.at(0)];
                                                }
                                                stringLinkBool[contactQIL.at(0)] = true;
                                                stringLinkContact[contactQIL.at(0)]->setIcon(generateContactIcon(getAvatarImage(contactQIL.at(1)),QImage(getIconPathForOnlineState(onlineState))));
                                            }
                                        }
                                    }
                                    else
                                    {
                                        stringLinkAvatar[contactQIL.at(0)] = contactQIL.at(1);
                                        stringLinkBool[contactQIL.at(0)] = false;
                                        if (!stringLinkImage.contains(contactQIL.at(1)))
                                        {
                                            stringLinkAvatar[contactQIL.at(0)] = "";
                                            arList.append(contactQIL.at(1));
                                        }
                                    }
                                }
                                else
                                {
                                    stringLinkAvatar[contactQIL.at(0)] = contactQIL.at(1);
                                    stringLinkBool[contactQIL.at(0)] = false;
                                    arList.append(contactQIL.at(1));
                                }
                            }
                        }
                        arList.removeDuplicates();
                    }
                    if (!arWrk)
                    {
                        at = new AvatarThread(arList,stringLinkImage.keys());
                        connect(at,SIGNAL(avatarInsert(QByteArray,QString)),this,SLOT(avatarInsert(QByteArray,QString)));
                        connect(at,SIGNAL(finished()),this,SLOT(setAvatarWorkFalse()));
                        at->start(QThread::LowPriority);
                        arWrk = true;
                    }
                }
                else if (request == "onlinestate" && id == 200)
                {
                    qDebug() << "Online state has changed to" << state << "with Icon" << getIconPathForTaskBarOnlineState(state);
                    QIcon taskbarIcon = QIcon(getIconPathForTaskBarOnlineState(state));
                    QPixmap userPixmap = QPixmap(getIconPathForTaskBarOnlineState(state));
                    ticon->setIcon(taskbarIcon);
                    ticon->setToolTip(QString(ProductName) + " (" + getTaskBarOnlineStateStringFromID(state) + ")");
                    ui->labUserStatusDesigned->setPixmap(userPixmap);
                }
                else if (request == "contactsrequests" && id == 200)
                {
                    qDebug() << "Contacts request list sended";
                    QStringList friendList = users.split("\n");
                    friendList.removeAll("");
                    friendList.removeAll("\r");
                    friendList.removeAll("\n");
                    friendList.removeAll("\r\n");
                    if (friendList.length() >= 1)
                    {
                        frList = friendList;
                        updateWelcomeLabel(myNickname);
                    }
                    else
                    {
                        frList.clear();
                        updateWelcomeLabel(myNickname);
                    }
                }
                else if (action == "sendmessage" && id == 200)
                {
                    qDebug() << "Maybe failed message";
                }
                else if (notification == "onlinestate")
                {
                    qDebug() << "Online state notification with the id" << state;
                    stringLinkOnlineState[username] = state;
                    stringLinkPixmapState[username] = getIconPathForOnlineState(state);
                    if (stringLinkContact.contains(username))
                    {
                        QListWidgetItem *contactItem = stringLinkContact[username];
                        int oldState = stringLinkOnlineState[username];
                        if (stringLinkAvatar.contains(username) && oldState != state)
                        {
                            contactItem->setIcon(generateContactIcon(getAvatarImage(stringLinkAvatar[username]),QImage(getIconPathForOnlineState(state))));
                        }
                    }
                    if (stringLinkChat.contains(username))
                    {
                        frmChat *cw = (frmChat*)stringLinkChat[username];
                        cw->setChatter(username,getCustomNick(username),stringLinkMessageState[username],myNickname,stringLinkPixmapState[username],state,stringLinkAvatar[username]);
                    }
                    QByteArray notificationPreMessage = QString(getCustomNick(username) + " " + QApplication::tr("changed status")).toUtf8();
                    if (notificationPreMessage.length() > 25)
                    {
                        notificationPreMessage = notificationPreMessage.left(23) + "..";
                    }
                    QString notificationMessage = toNotificationMessage(notificationPreMessage);
                    showNotification("<span style=\"color: blue;\">" + getCustomNick(username) + "</span><br>" + notificationMessage,QApplication::tr("Status changed"),"ocw\n" + username,true,QPixmap(getPixmapPathForNotificationOnlineState(state)));
                }
                else
                {
                    qDebug() << readstr;
                }
            }
            else
            {
                qDebug() << readstr;
            }
        }
    }
}

void frmLogin::setAvatarWorkFalse()
{
    arWrk = false;
    at->deleteLater();
}

void frmLogin::on_timerOA_tick()
{
    if (isLoggedIn)
    {
        if (fw->isLoggedIn())
        {
            fw->requestGetUserContactsWithAvatar();
            fw->requestGetUserContactsWithStates();
        }
    }
    QTimer::singleShot(20000,this,SLOT(on_timerOA_tick()));
}

void frmLogin::on_timerLC_tick()
{
    if (isLoggedIn)
    {
        if (!fw->isLoggedIn())
        {
            int ret = fw->loginUser(ui->txtName->text(),ui->txtPassword->text());
            if (ret == 200)
            {
                fw->requestGetUserOnlineState();
                fw->requestGetUserAvatar();
                updateWelcomeLabel(myNickname);
                if(isSayIC)
                {
                    ticon->showMessage(QApplication::tr("Reconnected"),QApplication::tr("%1 has relogged in your account").arg(ProductName),QSystemTrayIcon::Information,10000);
                    isSayIC = false;
                }
            }
            else if (ret == 404)
            {
                isLoggedIn = false;
                logoutUser();
                ticon->showMessage(QApplication::tr("Logged out"),QApplication::tr("Your Account data has been expired!"),QSystemTrayIcon::Warning,10000);
            }
            else if (ret == 500)
            {
                ticon->setIcon(QIcon(getIconPathForTaskBarOnlineState(8)));
                ticon->setToolTip(QString(ProductName) + " (" + getTaskBarOnlineStateStringFromID(8) + ")");
                ui->labUserStatusDesigned->setPixmap(QPixmap(getIconPathForTaskBarOnlineState(8)));
                if(!isSayIC)
                {
                    isSayIC = true;
                    foreach(QListWidgetItem *user, stringLinkContact.values())
                    {
                        QString username = contactLinkString[user];
                        stringLinkOnlineState[username] = 8;
                        user->setIcon(generateContactIcon(getAvatarImage(stringLinkAvatar[username]),QImage(getIconPathForOnlineState(8))));
                    }
                    ticon->showMessage(QApplication::tr("Disconnected"),QApplication::tr("Please check your Internet connection!"),QSystemTrayIcon::Warning,10000);
                }
            }
        }
    }
    QTimer::singleShot(10000,this,SLOT(on_timerLC_tick()));
}

bool frmLogin::isConnectedWithServer()
{
    if (isLoggedIn)
    {
        if (fw->isLoggedIn())
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    else
    {
        return false;
    }
}

void frmLogin::on_cmdLogin_clicked()
{
    loginUserDataFromLines(true, false);
}

void frmLogin::on_lwContacts_itemDoubleClicked(QListWidgetItem *item)
{
    if (contactLinkString.contains(item))
    {
        QString uname = contactLinkString[item];
        QStringList ulist = item->text().split("\n");
        openChatWindow(uname,ulist.at(0),ulist.at(1),stringLinkPixmapState[uname],stringLinkOnlineState[uname],stringLinkAvatar[uname]);
    }
}

void frmLogin::openChatWindow(QString username, QString nickname, QString userstate, QString pixmapstate, int onlinestate, QString avatarimage, bool minimized)
{
    if (!stringLinkChat.contains(username))
    {
        frmChat *cw = new frmChat();
        stringLinkChat[username] = cw;
        cw->setForm(this);
        cw->setChatter(username,nickname,userstate,myNickname,pixmapstate,onlinestate,avatarimage,true);
        cw->setWindowIcon(QIcon(ProductIcon));
        if (minimized == true)
        {
            cw->showMinimized();
        }
        else
        {
            cw->show();
            cw->activateWindow();
        }
    }
    else
    {
        frmChat *cw = (frmChat*)stringLinkChat[username];
        if (!cw->isMaximized())
        {
            cw->showNormal();
        }
        else
        {
            cw->showMaximized();
        }
        cw->activateWindow();
    }
}

int frmLogin::addUserContact(QString username)
{
    return fw->addUserContact(username);
}

int frmLogin::delUserContact(QString username)
{
    return fw->delUserContact(username);
}

int frmLogin::sendMessage(QString username, QString message)
{
    int ret = fw->sendMessageToUser(username,message);
    return ret;
}

int frmLogin::setUserPassword(QString oldpassword, QString newpassword)
{
    int ret = fw->setUserPassword(oldpassword,newpassword);
    return ret;
}

int frmLogin::setUserNick(QString nick)
{
    int ret = fw->setUserNick(nick);
    return ret;
}

int frmLogin::setUserMessageState(QString message)
{
    int ret = fw->setUserMessageState(message);
    return ret;
}

void frmLogin::updateFriendRequests()
{
    fw->requestGetUserContactsRequests();
}

void frmLogin::updateFriendRequestList(QString toAdd, QString toRemove)
{
    if (toAdd != "")
    {
        frList.append(toAdd);
        frList.sort();
    }
    if (toRemove != "")
    {
        frList.removeAll(toRemove);
    }
    updateWelcomeLabel(myNickname);
}

void frmLogin::removeMe(QString username)
{
    stringLinkChat.remove(username);
}

void frmLogin::on_cmdClose_clicked()
{
    this->close();
}

void frmLogin::on_labWelcomeNick_linkActivated(const QString &link)
{
    if (isConnectedWithServer())
    {
        if (link == "kmp://editprofile")
        {
            QString username = ui->txtName->text();
            QString profileStr = fw->getUserProfileInfo(username);
            if (profileStr.left(8) != "///Error")
            {
                QStringList profileList = profileStr.split("&nxve;");
                QList<QMap<QString,QString> > accasCList;
                QString messageState;
                QString msgState = fw->getUserMessageState();
                if (msgState.left(8) != "///Error")
                {
                    messageState = msgState;
                }
                QString signatureStr;
                QString contactsStr;
                QString accasStr;
                foreach(const QString& valStr, profileList)
                {
                    QStringList valList = valStr.split("&splt;");
                    if (valList.length() >= 2)
                    {
                        if (valList.at(0) == "contacts")
                        {
                            contactsStr = valList.at(1);
                        }
                        else if (valList.at(0) == "signature")
                        {
                            signatureStr = valList.at(1);
                        }
                        else if (valList.at(0) == "accas")
                        {
                            accasStr = valList.at(1);
                        }
                    }
                }
                if (accasStr != "")
                {
                    QStringList accasList = accasStr.split("&acln;");
                    foreach(const QString& accaValStr, accasList)
                    {
                        QMap<QString,QString> accaVal;
                        QStringList accaSubValList = accaValStr.split("&aclt;");
                        foreach(const QString& accaSubValStr, accaSubValList)
                        {
                            QStringList accaValList = accaSubValStr.split("&sxlt;");
                            if (accaValList.length() >= 2)
                            {
                                accaVal[accaValList.at(0)] = accaValList.at(1);
                            }
                        }
                        accasCList.append(accaVal);
                    }
                }
                frmProfile *pe = new frmProfile(this);
                pe->setForm(this);
                pe->setData(username,myNickname,messageState,contactsStr);
                pe->setMaps(accasCList);
                pe->setWindowIcon(QIcon(ProductIcon));
                pe->show();
                pe->exec();
                pe->deleteLater();
                delete pe;
            }
        }
        if (link == "kmp://friendrequests")
        {
            frmContactRequests *fr = new frmContactRequests(this);
            fr->setForm(this);
            fr->setContacts(frList);
            fr->setWindowIcon(QIcon(ProductIcon));
            fr->show();
            fr->exec();
            fr->deleteLater();
            delete fr;
        }
    }
    else
    {
        QMessageBox::information(this,QApplication::tr("Offline"),QApplication::tr("You are offline, please wait until you're online!"));
    }
}

void frmLogin::serverGroupChat()
{
#ifdef MACX
    QMessageBox::information(this,QApplication::tr("Server group chat"),QApplication::tr("Server group chat is disabled on Mac!"));
#else
#ifdef WIN32
    QMessageBox::information(this,QApplication::tr("Server group chat"),QApplication::tr("Server group chat is disabled on Windows!"));
#else
    QMessageBox::information(this,QApplication::tr("Server group chat"),QApplication::tr("Server group chat is disabled on Linux!"));
#endif
#endif
}

void frmLogin::updateWelcomeLabel(QString nick)
{
    myNickname = nick;
    ui->labUserNameDesigned->setText(nick);
    if (frList.length() == 1)
    {
        ui->labWelcomeNick->setText(QApplication::tr("Welcome %1 (<a href=\"kmp://editprofile\">Edit Profile</a>)<br>You have 1 (<a href=\"kmp://friendrequests\">Friend Request</a>)").arg(myNickname));
    }
    else if (frList.length() >= 2)
    {
        ui->labWelcomeNick->setText(QApplication::tr("Welcome %1 (<a href=\"kmp://editprofile\">Edit Profile</a>)<br>You have %2 (<a href=\"kmp://friendrequests\">Friend Requests</a>)").arg(myNickname,QString::number(frList.length())));
    }
    else
    {
        ui->labWelcomeNick->setText(QApplication::tr("Welcome %1 (<a href=\"kmp://editprofile\">Edit Profile</a>)").arg(myNickname));
    }
    QSettings settings(ProductVendor,ProductName);
    settings.beginGroup("Nick");
    settings.setValue(ui->txtName->text(),myNickname);
    settings.endGroup();
}

void frmLogin::on_lwContacts_customContextMenuRequested(const QPoint &pos)
{
    Q_UNUSED(pos);
    if (cContactList->count() == 0) return;
    if (!contactLinkString.contains(cContactList->currentItem())) return;
    QMenu *contextMenu = new QMenu();
    QAction *showProfile = contextMenu->addAction(QApplication::tr("Show profile"));
    connect(showProfile,SIGNAL(triggered()),this,SLOT(showProfile()));
    QAction *openChat = contextMenu->addAction(QApplication::tr("Open Chat"));
    connect(openChat,SIGNAL(triggered()),this,SLOT(openChat()));
    QAction *renameContact = contextMenu->addAction(QApplication::tr("Rename contact"));
    connect(renameContact,SIGNAL(triggered()),this,SLOT(triggerSetCustomNick()));
    QAction *removeContact = contextMenu->addAction(QApplication::tr("Remove contact"));
    connect(removeContact,SIGNAL(triggered()),this,SLOT(removeContact()));
    if (customNickAvailable(contactLinkString[cContactList->currentItem()]))
    {
        QAction *resetName = contextMenu->addAction(QApplication::tr("Reset name"));
        connect(resetName,SIGNAL(triggered()),this,SLOT(triggerRemoveCustomNick()));
    }
    contextMenu->popup(QCursor::pos());
}

void frmLogin::openChat()
{
    on_lwContacts_itemDoubleClicked(cContactList->currentItem());
}

void frmLogin::addContactItem(QString username)
{
    on_labContactsSearchReset_triggered();
    QListWidgetItem *contactItem = new QListWidgetItem(username + "\n");
    int contactState = 8;
    contactItem->setIcon(generateContactIcon(getAvatarImage(""),QImage(getIconPathForOnlineState(contactState))));
    stringLinkContact[username] = contactItem;
    stringLinkNick[username] = username;
    stringLinkOnlineState[username] = contactState;
    stringLinkPixmapState[username] = getIconPathForOnlineState(contactState);
    stringLinkMessageState[username] = contactState;
    contactLinkString[contactItem] = username;
    cContactList->addItem(contactItem);
    if (stringLinkChat.contains(username))
    {
        frmChat *cw = (frmChat*)stringLinkChat[username];
        cw->setChatter(username,username,"",myNickname,getIconPathForOnlineState(8),8,"");
    }
}

void frmLogin::addContact()
{
    if (isConnectedWithServer())
    {
        QInputDialog *inputDialog = new QInputDialog();
        QString input;
        QString ainput;
        int ret;
readdcontact:
        input = inputDialog->getText(this,QApplication::tr("Add contact"),QApplication::tr("Please type in the account name of your contact"),QLineEdit::Normal,"",0,inputDialog->windowFlags()^Qt::WindowContextHelpButtonHint^Qt::WindowMinMaxButtonsHint);
        if (input != "")
        {
            ainput = toAccountName(input.toUtf8());
            ret = fw->addUserContact(ainput);
            if (ret == 200)
            {
                addContactItem(ainput);
            }
            else if (ret == 404)
            {
                QMessageBox::information(this,QApplication::tr("Add contact"),QApplication::tr("The account %1 don't exists!").arg(input));
                goto readdcontact;
            }
            else
            {
                QMessageBox::warning(this,QApplication::tr("Add contact"),QApplication::tr("Add contact failed!"));
            }
        }
        inputDialog->deleteLater();
        delete inputDialog;
    }
    else
    {
        QMessageBox::information(this,QApplication::tr("Offline"),QApplication::tr("You are offline, please wait until you're online!"));
    }
}

void frmLogin::addUserContactWithItem(QString username, QWidget *wthis)
{
    QString ainput = toAccountName(username.toUtf8());
    int ret = fw->addUserContact(ainput);
    if (ret == 200)
    {
        addContactItem(ainput);
    }
    else if (ret == 404)
    {
        QMessageBox::information(wthis,QApplication::tr("Add contact"),QApplication::tr("The account %1 don't exists!").arg(username));
    }
    else
    {
        QMessageBox::warning(wthis,QApplication::tr("Add contact"),QApplication::tr("Add contact failed!"));
    }
}

void frmLogin::removeContact()
{
    if (isConnectedWithServer())
    {
        if (contactLinkString.contains(cContactList->currentItem()))
        {
            QString username = contactLinkString[cContactList->currentItem()];
            int ret = QMessageBox::question(this,QApplication::tr("Remove contact"),QApplication::tr("Are you sure to remove %1 from your Contacts?").arg(stringLinkNick[username]),QMessageBox::Yes, QMessageBox::No);
            if (ret == QMessageBox::Yes)
            {
                if (fw->delUserContact(username) == 200)
                {
                    QListWidgetItem *citem = stringLinkContact[username];
                    contactLinkString.remove(citem);
                    if (stringLinkChat.contains(username))
                    {
                        frmChat* cw = (frmChat*)stringLinkChat[username];
                        cw->close();
                        stringLinkChat.remove(username);
                    }
                    stringLinkContact.remove(username);
                    stringLinkNick.remove(username);
                    stringLinkOnlineState.remove(username);
                    stringLinkPixmapState.remove(username);
                    stringLinkMessageState.remove(username);
                    delete citem;
                }
                else
                {
                    QMessageBox::warning(this,QApplication::tr("Remove contact"),QApplication::tr("Can't remove %1 from your Contacts!").arg(stringLinkNick[username]));
                }
            }
        }
    }
    else
    {
        QMessageBox::information(this,QApplication::tr("Offline"),QApplication::tr("You are offline, please wait until you're online!"));
    }
}

QString frmLogin::getCustomNick(QString username)
{
    QSettings settings(ProductVendor,ProductName);
    settings.beginGroup("Nick");
    QString normalNick;
    if (stringLinkNick.contains(username))
    {
        normalNick = settings.value(username, stringLinkNick[username]).toString();
    }
    else
    {
        normalNick = settings.value(username, username).toString();
    }
    settings.endGroup();
    settings.beginGroup("CustomNick");
    QString nickname = settings.value(username, normalNick).toString();
    settings.endGroup();
    if (nickname.trimmed() == "") {nickname = normalNick;}
    return nickname;
}

QString frmLogin::toAccountName(QByteArray account)
{
    QString text = QString::fromUtf8(account);
    text.replace(QString::fromUtf8("&"),"&amp;");
    text.replace(QString::fromUtf8("<"),"&lt;");
    text.replace(QString::fromUtf8(">"),"&gt;");
    text.replace(QString::fromUtf8("\""),"&quot;");
    text.replace(QString::fromUtf8("ä"),"&auml;");
    text.replace(QString::fromUtf8("ö"),"&ouml;");
    text.replace(QString::fromUtf8("ü"),"&uuml;");
    text.replace(QString::fromUtf8("Ä"),"&Auml;");
    text.replace(QString::fromUtf8("Ö"),"&Ouml;");
    text.replace(QString::fromUtf8("Ü"),"&Uuml;");
    text.replace(QString::fromUtf8("ß"),"&szlig;");
    text.replace(QString::fromUtf8("€"),"&euro;");
    text.replace(QString::fromUtf8("§"),"&sect;");
    text.replace(QString::fromUtf8("©"),"&copy;");
    text.replace(QString::fromUtf8("®"),"&reg;");
    text.replace(QString::fromUtf8("°"),"&deg;");
    text.replace(QString::fromUtf8("²"),"&sup2;");
    text.replace(QString::fromUtf8("³"),"&sup3;");
    text.replace(QString::fromUtf8("\r\n"),"<br>");
    text.replace(QString::fromUtf8("\r"),"<br>");
    text.replace(QString::fromUtf8("\n"),"<br>");
    return text;
}

QString frmLogin::toNotificationMessage(QByteArray notification)
{
    return toAccountName(notification);
}

QByteArray frmLogin::fromMessage(QString message)
{
    QByteArray text = message.toUtf8();
    text.replace("&auml;","ä");
    text.replace("&ouml;","ö");
    text.replace("&uuml;","ü");
    text.replace("&Auml;","Ä");
    text.replace("&Ouml;","Ö");
    text.replace("&Uuml;","Ü");
    text.replace("&szlig;","ß");
    text.replace("&euro;","€");
    text.replace("&sect;","§");
    text.replace("&copy;","©");
    text.replace("&reg;","®");
    text.replace("&deg;","°");
    text.replace("&sup2;","²");
    text.replace("&sup3;","³");
    text.replace("<br>","\n");
    text.replace("&quot;","\"");
    text.replace("&lt;","<");
    text.replace("&gt;",">");
    text.replace("&amp;","&");
    return text;
}

void frmLogin::playChatIn()
{
    if (QFile::exists("ChatIn.wav"))
    {
        QSound::play("ChatIn.wav");
    }
#ifdef ChatIn
    else if (QFile::exists(ChatIn))
    {
        QSound::play(ChatIn);
    }
#endif
    else
    {
        if (QFile::copy(":/sound/ChatIn.wav","ChatIn.wav")) {QSound::play("ChatIn.wav");}
    }
}

void frmLogin::on_cbStayLoggedIn_stateChanged(int arg1)
{
    Q_UNUSED(arg1);
    if (ui->cbStayLoggedIn->isChecked())
    {
        ui->cbStartWithWindows->setChecked(isSWW);
        ui->cbStartWithWindows->setEnabled(true);
    }
    else
    {
        if (ui->cbStartWithWindows->isChecked())
        {
            isSWW = true;
            ui->cbStartWithWindows->setChecked(false);
            ui->cbStartWithWindows->setEnabled(false);
        }
        else
        {
            isSWW = false;
            ui->cbStartWithWindows->setEnabled(false);
        }
    }
}

void frmLogin::setCustomNick(QString username, QString nickname)
{
    QSettings settings(ProductVendor,ProductName);
    settings.beginGroup("CustomNick");
    if (nickname.trimmed() != "")
    {
        settings.setValue(username,nickname.trimmed());
    }
    else
    {
        settings.remove(username);
    }
    settings.endGroup();
}

bool frmLogin::customNickAvailable(QString username)
{
    QSettings settings(ProductVendor,ProductName);
    settings.beginGroup("CustomNick");
    bool contain = settings.contains(username);
    if (contain)
    {
        QString nickname = settings.value(username,"").toString();
        if (nickname.trimmed() == "") {contain = false;}
    }
    settings.endGroup();
    return contain;
}

void frmLogin::triggerSetCustomNick()
{
    if (contactLinkString.contains(cContactList->currentItem()))
    {
        QInputDialog *inputDialog = new QInputDialog();
        QString uname = contactLinkString[cContactList->currentItem()];
        QString newNick = inputDialog->getText(this,QApplication::tr("Rename contact"),QApplication::tr("Please type in the new contact name"),QLineEdit::Normal,getCustomNick(uname),0,inputDialog->windowFlags()^Qt::WindowContextHelpButtonHint^Qt::WindowMinMaxButtonsHint);
        inputDialog->deleteLater();
        delete inputDialog;
        if (newNick.trimmed() != "")
        {
            setCustomNick(uname,newNick.trimmed());
            cContactList->currentItem()->setText(newNick + "\n" + QString::fromUtf8(fromMessage(stringLinkMessageState[uname])));
            if (stringLinkChat.contains(uname))
            {
                frmChat *cw = (frmChat*)stringLinkChat[uname];
                cw->setChatter(uname,getCustomNick(uname),stringLinkMessageState[uname],myNickname,stringLinkPixmapState[uname],stringLinkOnlineState[uname],stringLinkAvatar[uname]);
            }
        }
    }
}

void frmLogin::triggerRemoveCustomNick()
{
    if (contactLinkString.contains(cContactList->currentItem()))
    {
        QString uname = contactLinkString[cContactList->currentItem()];
        setCustomNick(uname,"");
        cContactList->currentItem()->setText(getCustomNick(uname) + "\n" + QString::fromUtf8(fromMessage(stringLinkMessageState[uname])));
        if (stringLinkChat.contains(uname))
        {
            frmChat *cw = (frmChat*)stringLinkChat[uname];
            cw->setChatter(uname,getCustomNick(uname),stringLinkMessageState[uname],myNickname,stringLinkPixmapState[uname],stringLinkOnlineState[uname],stringLinkAvatar[uname]);
        }
    }
}

QString frmLogin::getUserAvatar()
{
    if (stringLinkAvatar.contains(ui->txtName->text()))
    {
        return stringLinkAvatar[ui->txtName->text()];
    }
    else
    {
        return "";
    }

}

QString frmLogin::getUserName()
{
    return ui->txtName->text();
}

void frmLogin::serverChatTurnedOff()
{
}

void frmLogin::on_labRegister_linkActivated(const QString &link)
{
    if (link == "kmp://register")
    {
        //ui->swTabs->setCurrentIndex(2);
        //setRegisterCaptcha();
        QDesktopServices::openUrl(QUrl("http://msg.keppe.org/user-register.php"));
    }
}

void frmLogin::on_cmdStop_clicked()
{
    this->close();
}

void frmLogin::on_cmdBack_clicked()
{
    if (designedMode)
    {
        ui->swTabs->setCurrentIndex(3);
    }
    else
    {
        ui->swTabs->setCurrentIndex(0);
    }
    ui->labRegisterCaptcha->setText("Captcha: Not loaded");
}

void frmLogin::on_cmdRegister_clicked()
{
    //Register
}

void frmLogin::on_cmdRegisterCaptchaGenerateNew_clicked()
{
    ui->txtRegisterCaptcha->clear();
    setRegisterCaptcha();
    ui->txtRegisterCaptcha->setFocus();
}

void frmLogin::setRegisterCaptcha()
{
    QCryptographicHash codeHash(QCryptographicHash::Sha1);
    codeHash.addData(QDateTime::currentDateTime().toString(Qt::TextDate).toUtf8());
    QByteArray codeByte = codeHash.result().toHex();
    QString codeString = QString::fromUtf8(codeByte,10);
    codeString.insert(9,"+");
    codeString.insert(8,"+");
    codeString.insert(7,"+");
    codeString.insert(6,"+");
    codeString.insert(5,"+");
    codeString.insert(4,"+");
    codeString.insert(3,"+");
    codeString.insert(2,"+");
    codeString.insert(1,"+");
    captchaCode = codeString;
    QNetworkAccessManager *http = new QNetworkAccessManager();
    QNetworkReply *treply = http->get(QNetworkRequest(QUrl("http://msg.keppe.org/captcha-gui.php?code=" + captchaCode)));
    QEventLoop loop;
    QTimer::singleShot(5000, &loop, SLOT(quit()));
    QObject::connect(treply, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec();
    QByteArray captcha = treply->readAll().toBase64();
    ui->labRegisterCaptcha->setText("<img src=\"data:image/png;base64," + captcha + "\"/>");
}

void frmLogin::showNotification(QString text, QString title, QString noteBack, bool updatePixmap, QPixmap pixmap)
{
    NotificationWidget *nw = new NotificationWidget();
    nw->setNotificationText(text);
    nw->setNotificationTitle(title);
    nw->setNotificationBack(noteBack);
    if (updatePixmap)
    {
        nw->setNotificationPixmap(pixmap);
    }
    nw->setWindowIcon(QIcon(ProductIcon));
    nw->setNotificationShow();
    connect(nw,SIGNAL(notificationPressed(QString)),this,SLOT(noteBack(QString)));
    connect(nw,SIGNAL(finished(int)),this,SLOT(endNotification()));
}

void frmLogin::endNotification()
{
    NotificationWidget *nw = (NotificationWidget*)sender();
    nw->deleteLater();
    delete nw;
}

void frmLogin::noteBack(QString backVal)
{
    QStringList backList = backVal.split("\n");
    if (backList.length() >= 2)
    {
        if (backList.at(0) == "ocw")
        {
            QString username = backList.at(1);
            openChatWindow(username,getCustomNick(username),stringLinkMessageState[username],stringLinkPixmapState[username], stringLinkOnlineState[username], stringLinkAvatar[username], false);
            if (stringLinkChat.contains(username))
            {
                frmChat *cw = (frmChat*)stringLinkChat[username];
                cw->activateWindow();
                cw->setChatFocus();
            }
        }
    }
}

void frmLogin::showProfile()
{
    if (isConnectedWithServer())
    {
        if (contactLinkString.contains(cContactList->currentItem()))
        {
            QString username = contactLinkString[cContactList->currentItem()];
            QString profileStr = fw->getUserProfileInfo(username);
            if (profileStr.left(8) != "///Error")
            {
                QStringList profileList = profileStr.split("&nxve;");
                QList<QMap<QString,QString> > accasCList;
                QString nick = getCustomNick(username);
                if (nick.right(1) != "s") {nick.append("'s");}
                QString messageState;
                if (stringLinkMessageState.contains(username)){messageState = stringLinkMessageState[username];}
                QString signatureStr;
                QString contactsStr;
                QString accasStr;
                foreach(const QString& valStr, profileList)
                {
                    QStringList valList = valStr.split("&splt;");
                    if (valList.length() >= 2)
                    {
                        if (valList.at(0) == "contacts")
                        {
                            contactsStr = valList.at(1);
                        }
                        else if (valList.at(0) == "signature")
                        {
                            signatureStr = valList.at(1);
                        }
                        else if (valList.at(0) == "accas")
                        {
                            accasStr = valList.at(1);
                        }
                    }
                }
                if (accasStr != "")
                {
                    QStringList accasList = accasStr.split("&acln;");
                    foreach(const QString& accaValStr, accasList)
                    {
                        QMap<QString,QString> accaVal;
                        QStringList accaSubValList = accaValStr.split("&aclt;");
                        foreach(const QString& accaSubValStr, accaSubValList)
                        {
                            QStringList accaValList = accaSubValStr.split("&sxlt;");
                            if (accaValList.length() >= 2)
                            {
                                accaVal[accaValList.at(0)] = accaValList.at(1);
                            }
                        }
                        accasCList.append(accaVal);
                    }
                }
                frmProfileInfo *pi = new frmProfileInfo(this);
                pi->setUser(username);
                pi->setNick(getCustomNick(username));
                pi->setContacts(contactsStr);
                pi->setSignature(signatureStr);
                pi->setMessageState(messageState);
                pi->setMaps(accasCList);
                pi->setWindowIcon(QIcon(ProductIcon));
                pi->setWindowTitle(QApplication::tr("%1 profile").arg(nick));
                pi->show();
                pi->exec();
                pi->deleteLater();
                delete pi;
            }
            else
            {
                QMessageBox::warning(this,QApplication::tr("Show profile"),QApplication::tr("Can't get Profile Image!"));
            }
        }
    }
}

QStringList frmLogin::putStringToStringList(QString string)
{
    QStringList strlist;
    strlist << string;
    return strlist;
}

QString frmLogin::getMessengerFrameworkVersion()
{
    return fw->getClassVersion();
}

QString frmLogin::getGuiFrameworkVersion()
{
    KGuiFw *guifw = new KGuiFw(this);
    QString guifwver = guifw->getLibraryVersion();
    guifw->deleteLater();
    delete guifw;
    return guifwver;
}

#ifdef UPDATE_MANAGER
void frmLogin::setUpdateThread(UpdateThread *uThread)
{
    ut = uThread;
}

void frmLogin::setUpdateWindow(frmUpdate *uWindow)
{
    uw = uWindow;
}

void frmLogin::checkUpdate()
{
    bool updateAvailable = ut->checkUpdate();
    if (updateAvailable)
    {
        ut->emitUpdate();
    }
    else
    {
        QMessageBox::information(this,QString("%1 Update").arg(ProductName),QApplication::tr("You have the current version of %1!").arg(ProductName));
    }
}

void frmLogin::enableUpdateNotification()
{
    uw->enableUpdateNotificationButton();
    if (!ut->isRunning())
    {
        ut->start();
    }
}

void frmLogin::disableUpdateNotification()
{
    uw->disableUpdateNotificationButton();
    if (ut->isRunning())
    {
        ut->terminate();
    }
}
#endif

void frmLogin::on_labDesignedLogin_mousePress(QMouseEvent *)
{
    // Not text here
}

void frmLogin::on_labDesignedLogin_mouseRelease(QMouseEvent *)
{
    if (ui->labDesignedLogin->rect().contains(ui->labDesignedLogin->mapFromGlobal(QCursor::pos())))
    {
        ui->txtName->setText(ui->txtNameDesigned->text());
        ui->txtPassword->setText(ui->txtPasswordDesigned->text());
        ui->cbStayLoggedIn->setChecked(ui->cbStayLoggedInDesigned->isChecked());
        ui->cbStartWithWindows->setChecked(ui->cbStartWithWindowsDesigned->isChecked());
        loginUserDataFromLines(true,false);
    }
}

void frmLogin::on_lwContactsDesigned_customContextMenuRequested(const QPoint &pos)
{
    on_lwContacts_customContextMenuRequested(pos);
}

void frmLogin::on_lwContactsDesigned_itemDoubleClicked(QListWidgetItem *item)
{
    on_lwContacts_itemDoubleClicked(item);
}

void frmLogin::on_txtContactsSearch_textEdited(const QString &arg1)
{
    QString searchText = arg1;
    searchText = searchText.toLower();
    if (searchText != "")
    {
        foreach(const QString &contact, contactLinkString.values())
        {
            QString contactName = contact;
            QString contactNick = getCustomNick(contact).toLower();
            contactName = contactName.toLower();
            if (contactName.startsWith(searchText) || contactNick.startsWith(searchText))
            {
                stringLinkContact[contact]->setHidden(false);
            }
            else
            {
                stringLinkContact[contact]->setHidden(true);
            }
        }
        ui->labContactsSearchReset->setVisible(true);
    }
    else
    {
        foreach(const QString &contact, contactLinkString.values())
        {
            stringLinkContact[contact]->setHidden(false);
        }
        ui->labContactsSearchReset->setVisible(false);
    }
}

void frmLogin::on_labContactsSearchReset_mouseRelease(QMouseEvent *)
{
    on_labContactsSearchReset_triggered();
}

void frmLogin::on_labContactsSearchReset_triggered()
{
    if (ui->labContactsSearchReset->rect().contains(ui->labContactsSearchReset->mapFromGlobal(QCursor::pos())))
    {
        ui->txtContactsSearch->clear();
        cContactList->setFocus();
        on_txtContactsSearch_textEdited("");
    }
}

void frmLogin::on_labUserNameDesigned_mouseRelease(QMouseEvent *)
{
    //on_frStatus_mouseRelease(ev);
}

void frmLogin::on_labUserStatusDesigned_mouseRelease(QMouseEvent *)
{
    //on_frStatus_mouseRelease(ev);
}

void frmLogin::on_frStatus_mouseRelease(QMouseEvent *)
{
    if (ui->frStatus->rect().contains(ui->frStatus->mapFromGlobal(QCursor::pos())))
    {
        editProfile();
    }
}

bool frmLogin::uploadAvatar(QImage avatar)
{
    if (isLoggedIn)
    {
        if (fw->isLoggedIn())
        {
            qDebug() << "Uploading...";
            return fw->uploadAvatar(ui->txtName->text(),ui->txtPassword->text(),avatar);
        }
        else
        {
            return false;
        }
    }
    else
    {
        return false;
    }
}

QImage frmLogin::getAvatarImage(QString avatarImage)
{
    if (stringLinkImage.contains(avatarImage))
    {
        return stringLinkImage[avatarImage];
    }
    else
    {
        return defaultAvatar;
    }
}

void frmLogin::avatarInsert(QByteArray avatarPixmap, QString avatarImage)
{
    stringLinkImage[avatarImage] = QImage::fromData(avatarPixmap);
}

QIcon frmLogin::generateContactIcon(QImage avatar, QImage state)
{
    if (bigIcon)
    {
        QPixmap *iconPixmap = new QPixmap(68,54);
        iconPixmap->fill(Qt::transparent);
        QPainter drawPainter(iconPixmap);
        QImage avatar64 = avatar.scaled(48,48,Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
        QImage state16 = state.scaled(16,16,Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
        drawPainter.drawImage(QPoint(0,3),avatar64);
        drawPainter.drawImage(QPoint(52,19),state16);
        return QIcon(*(iconPixmap));
    }
    else
    {
        QPixmap *iconPixmap = new QPixmap(52,38);
        iconPixmap->fill(Qt::transparent);
        QPainter drawPainter(iconPixmap);
        QImage avatar64 = avatar.scaled(32,32,Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
        QImage state16 = state.scaled(16,16,Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
        drawPainter.drawImage(QPoint(0,3),avatar64);
        drawPainter.drawImage(QPoint(36,11),state16);
        return QIcon(*(iconPixmap));
    }
}
